<template>
  <div class="app-container">
    <el-card>
      <!--用户数据-->
      <el-form :model="queryParams" ref="queryForm" size="small" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="实 践 课 程">
              <el-select v-model="queryParams.practiceType" placeholder="请选择" clearable @change="handleQuery">
                <el-option v-for="item in practiceTypeList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="实践任务名称">
              <el-input v-model.trim="queryParams.taskName" placeholder="输入内容" clearable @keyup.enter.native="handleQuery"
                @input="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="任 务 状 态">
              <el-select v-model="queryParams.taskStatus" placeholder="请选择" clearable @change="handleQuery">
                <el-option v-for="item in taskStatusList" :key="item.id" :label="item.type" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发 布 时 间">
              <el-date-picker v-model="dateRangeQuery" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
                @change="handleQuery" style="width: 100%" start-placeholder="开始日期"
                end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item label="参 与 方 式">
              <el-select v-model="queryParams.participationWay" placeholder="请选择" clearable @change="handleQuery">
                <el-option label="指定学生参与" value="1" />
                <el-option label="学生自选报名" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="queryParams.participationWay != 1">
            <el-form-item label="报 名 状 态">
              <el-select v-model="queryParams.applyStatus" placeholder="请选择" clearable @change="handleQuery">
                <el-option v-for="item in applyStatusList" :key="item.id" :label="item.type" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建人/发布人">
              <el-input v-model.trim="queryParams.releaseByName" placeholder="输入内容" clearable
                @keyup.enter.native="handleQuery" @input="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所 属 学 期">
              <el-select v-model="queryParams.semesterConfigId" placeholder="请选择" clearable @change="handleQuery">
                <el-option v-for="item in querySemesterList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-form-item label-width="50px">
              <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['project:task:add']">新增任务</el-button>
        </el-col>
      </el-row>
      <div class="double-table-container">
        <div class="header-table-wrapper">
          <el-table ref="headerTable" :data="[]" @sort-change="sortChange">
            <el-table-column type="index" width="50" align="center" />
            <el-table-column label="实践任务名称" width="150" align="center" key="taskName" prop="taskName" sortable="custom"
              :show-overflow-tooltip="true" style="white-space: nowrap;" />
            <el-table-column label="实践课程" width="100" align="center" />
            <el-table-column label="任务次数" width="100" align="center" key="taskNumber" prop="taskNumber"
              sortable="custom" />
            <el-table-column label="积分上限" width="100" align="center" key="pointsCap" prop="pointsCap" sortable="custom"
              style="white-space: nowrap;" />
            <el-table-column label="学生参与方式" width="120" align="center" key="participationWay" prop="participationWay">
              <template slot-scope="scope">
                {{ scope.row.participationWay == 1 ? '指定学生参与' : scope.row.participationWay == 2 ? '学生自选报名' : '' }}
              </template>
            </el-table-column>
            <el-table-column label="人数限制" width="80" align="center" key="peoplesNumberAstrict"
              prop="peoplesNumberAstrict" />
            <el-table-column label="学生范围(人数)" width="120" align="center" key="studentIds" prop="studentIds" />
            <el-table-column label="报名时间" width="120" align="center" key="applyTime" />
            <el-table-column label="所属学期" width="150" align="center" key="semesterConfigName" prop="semesterConfigName" />
            <el-table-column label="发布时间" width="150" align="center" key="createTime" prop="createTime" />
            <el-table-column label="创建人/发布人" width="150" align="center" key="nickName" prop="nickName" />
            <el-table-column label="任务状态" width="150" align="center" key="status" />
            <el-table-column label="报名状态" width="150" align="center" key="applyStatus" />
            <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width" fixed="right" />
          </el-table>
        </div>
        <div class="body-table-wrapper">
          <el-table ref="bodyTable" v-loading="loading" :data="tableList" @sort-change="sortChange">
            <el-table-column type="index" width="50" align="center" />
            <el-table-column label="实践任务名称" width="150" align="center" key="taskName" prop="taskName" sortable="custom"
              :show-overflow-tooltip="true" style="white-space: nowrap;" />
            <el-table-column label="实践课程" width="100" align="center">
              <template slot-scope="scope">
                {{ (practiceTypeList.find(v => v.id == scope.row.practiceType) || {}).name }}
              </template>
            </el-table-column>
            <el-table-column label="任务次数" width="100" align="center" key="taskNumber" prop="taskNumber"
              sortable="custom" />
            <el-table-column label="积分上限" width="100" align="center" key="pointsCap" prop="pointsCap" sortable="custom" />
            <el-table-column label="学生参与方式" width="120" align="center" key="participationWay" prop="participationWay">
              <template slot-scope="scope">
                {{ scope.row.participationWay == 1 ? '指定学生参与' : scope.row.participationWay == 2 ? '学生自选报名' : '' }}
              </template>
            </el-table-column>
            <el-table-column label="人数限制" width="80" align="center" key="peoplesNumberAstrict"
              prop="peoplesNumberAstrict">
              <template slot-scope="scope">
                {{
                  scope.row.participationWay == 1 ? '-' : scope.row.participationWay == 2 ? scope.row.peoplesNumberAstrict :
                  ''
                }}
              </template>
            </el-table-column>
            <el-table-column label="学生范围(人数)" width="120" align="center" key="studentIds" prop="studentIds">
              <template slot-scope="scope">
                {{ (scope.row.studentIds || []).length }}
              </template>
            </el-table-column>
            <el-table-column label="报名时间" width="120" align="center" key="applyTime">
              <template slot-scope="scope">
                {{
                  scope.row.participationWay == 1 ? '-' : scope.row.participationWay == 2 ?
                  scope.row.applyStartTime.slice(0,
                    10) + '~'
                  + scope.row.applyEndTime.slice(0, 10) : ''
                }}
              </template>
            </el-table-column>
            <el-table-column label="所属学期" width="150" align="center" key="semesterConfigName" prop="semesterConfigName" />
            <el-table-column label="发布时间" width="150" align="center" key="createTime" prop="createTime">
              <template slot-scope="scope">
                {{ scope.row.createTime.slice(0, 16) }}
              </template>
            </el-table-column>
            <el-table-column label="创建人/发布人" width="150" align="center" key="nickName" prop="nickName">
              <template slot-scope="scope">
                {{ scope.row.taskStatus != 0 ? scope.row.releaseByName : scope.row.nickName }}({{ scope.row.taskStatus !=
                  0
                  ?
                  scope.row.releaseJsNumber : scope.row.jsNumber }})
              </template>
            </el-table-column>
            <el-table-column label="任务状态" width="150" align="center" key="status">
              <template slot-scope="scope">
                {{ taskStatusList.find(v => v.id == scope.row.taskStatus).type }}
              </template>
            </el-table-column>
            <el-table-column label="报名状态" width="150" align="center" key="applyStatus">
              <template slot-scope="scope">
                {{
                  (applyStatusList.find(v => v.id == scope.row.applyStatus) || {}).type || '-'
                }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width" fixed="right">
              <template slot-scope="scope">
                <el-button v-show="scope.row.taskStatus != 0" type="text" @click="handleUpdate(scope.row)"
                  v-hasPermi="['project:task:query']">详情</el-button>
                <el-button v-show="scope.row.taskStatus == 0" type="text" @click="handleUpdate(scope.row)"
                  v-hasPermi="['project:task:add']">修改</el-button>
                <el-button v-show="scope.row.taskStatus != 0" style="color: #f56c6c;" type="text"
                  @click="handleWithdraw(scope.row)" v-hasPermi="['project:task:edit']">撤回</el-button>
                <el-button v-show="scope.row.taskStatus == 0" style="color: #f56c6c;" type="text"
                  @click="handleDelete(scope.row)" v-hasPermi="['project:task:add']">删除</el-button>
                <el-button v-show="scope.row.taskStatus != 0" type="text" @click="tiao(scope.row)"
                  v-hasPermi="['practice:user:performanceXy']">完成情况</el-button>
                <el-button v-show="scope.row.participationWay == 2 && scope.row.taskStatus != 0" type="text"
                  @click="applicaView(scope.row)" v-hasPermi="['practice:user:registration']">报名情况</el-button>
                <el-button v-show="scope.row.taskStatus == 0" type="text" @click="submitList(scope.row)"
                  v-hasPermi="['project:task:add']">发布</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </el-card>
    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body :before-close="beforeClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-card style="margin-top: 5px;margin-bottom: 5px;">
          <el-row>
            <el-col :span="24">
              <div class="inforClass">基础信息</div>
            </el-col>
            <el-col :span="24">
              <el-form-item label="实践任务名称" prop="taskName">
                <el-input v-model="form.taskName" placeholder="请输入任务名称" maxlength="30" :readonly="title == '查看任务'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="实践课程" prop="practiceType">
                <el-select v-model="form.practiceType" placeholder="请选择实践课程" clearable style="width:100%"
                  :disabled="title == '查看任务'">
                  <el-option v-for="item in practiceTypeList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="积分上限" prop="pointsCap">
                <el-select v-model="form.pointsCap" placeholder="请选择积分上限" clearable style="width:100%"
                  :disabled="title == '查看任务'">
                  <el-option v-for="item in integralList" :key="item" :label="item" :value="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="任务时间" prop="dateRangeQuery">
                <el-date-picker v-model="form.dateRangeQuery" style="width: 100%" value-format="yyyy-MM-dd"
                  type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                  :readonly="title == '查看任务'" @input="$forceUpdate()" @change="getSemes"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属学期">
                <el-select v-model="form.semesterConfigId" :placeholder="title == '查看任务' ? '' : '请选择任务时间'"
                  style="width:100%" :readonly="title == '查看任务'" @change="$forceUpdate()">
                  <el-option v-for="item in semesterList" :label="item.name" :value="item.id"
                    :disabled="title == '查看任务'" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="title == '查看任务'">
            <el-col :span="12">
              <el-form-item label="发布时间">
                <el-input v-model="form.releaseTime" placeholder="" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发布人">
                <el-input v-model="form.nickName" placeholder="" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="若审核不通过扣除积分数" label-width="180px">
                <el-input v-model="form.noPassPoints" placeholder="请输入扣除积分数" :readonly="title == '查看任务'"
                  @input="handleInputPassPoints" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        <el-card style="margin-top: 5px;margin-bottom: 5px;">
          <el-row>
            <el-col :span="24">
              <div class="inforClass">参与设置</div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="参与方式" prop="participationWay">
                <el-select v-model="form.participationWay" :placeholder="title == '查看任务' ? '' : '请选择参与方式'"
                  style="width:100%" :readonly="title == '查看任务'" @change="changeWay">
                  <el-option label="指定学生参与" value="1" :disabled="title == '查看任务'" />
                  <el-option label="学生自选报名" value="2" :disabled="title == '查看任务'" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.participationWay == '2'">
              <el-form-item label="报名审核" prop="applyCheck">
                <el-select v-model="form.applyCheck" placeholder="请选择" :clearable="title != '查看任务'"
                  :readonly="title == '查看任务'" @input="$forceUpdate()">
                  <el-option label="无需审核，直接参与" value="0" :disabled="title == '查看任务'" clearable="false" />
                  <el-option label="需要审核通过后参与" value="1" :disabled="title == '查看任务'" clearable="false" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.participationWay != '2'">
              <el-form-item label="任务次数(次)" prop="taskNumber">
                <el-select v-model="form.taskNumber" placeholder="请选择任务次数" clearable style="width:100%"
                  :disabled="title == '查看任务'">
                  <el-option v-for="item in taksnNumList" :key="item" :label="item" :value="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="form.participationWay == '2'">
            <el-col :span="12">
              <el-form-item label="报名时间" prop="dateRangeApply">
                <el-date-picker v-model="form.dateRangeApply" style="width: 100%" value-format="yyyy-MM-dd"
                  type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                  :readonly="title == '查看任务'" @input="$forceUpdate()"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="人数限制" prop="peoplesNumberAstrict">
                <el-input v-model="form.peoplesNumberAstrict" placeholder="请输入限制人数" :readonly="title == '查看任务'"
                  @input="handleInput">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="form.participationWay == '2'">
            <el-col :span="12">
              <el-form-item label="爽约扣除积分数">
                <el-input v-model="form.applyPassCancelPoints" placeholder="请输入扣除积分" :readonly="title == '查看任务'"
                  @input="handleInputPoints">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="学生范围" prop="faceXy">
                <el-button type="primary" plain @click="selecStudent">
                  选择学生 ({{ studentIds.length }})
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        <el-card style="margin-top: 5px;margin-bottom: 5px;">
          <el-row>
            <el-col :span="24">
              <div class="inforClass">任务要求与注意事项</div>
            </el-col>
            <el-col :span="24">
              <el-form-item label="任务要求" prop="taskRequire">
                <el-input v-model="form.taskRequire" placeholder="请输入任务要求" resize="none" type="textarea"
                  :autosize="{ minRows: 3, maxRows: 5 }" :readonly="title == '查看任务'" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="注意事项">
                <el-input v-model="form.mattersNeedAttention" placeholder="请输入注意事项" resize="none" type="textarea"
                  :autosize="{ minRows: 3, maxRows: 5 }" :readonly="title == '查看任务'" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        <el-card style="margin-top: 5px;margin-bottom: 5px;"
          v-if="title != '查看任务' || (title == '查看任务' && form.fileList.length > 0)">
          <el-row>
            <el-col :span="24">
              <div class="inforClass">附件</div>
            </el-col>
            <el-col :span="24">
              <el-form-item label="" v-if="title != '查看任务'" id="fileId">
                <el-upload class="upload-demo" ref="fileUpload" :action="uploadFileUrl" :limit="5" :headers="headers"
                  :on-error="handleUploadError" :on-remove="handleDeleteFile" :on-exceed="handleExceed"
                  :before-upload="handleBeforeUpload" :file-list="fileList" :on-success="handleUploadSuccess" accept>
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">
                    可上传word、pdf、excel、mp4、jpg、png,
                    附件总上传不超过6M(每张图片大小建议不超过1M)
                  </div>
                </el-upload>
              </el-form-item>
              <el-form-item label="" id="fileId" v-else>
                <div class="fileImage">
                  <div v-for="item in (form.fileList || fileList)" :key="item.id">
                    <img :src="item.fileSrc" alt=""
                      v-if="item.fileType == 'png' || item.fileType == 'jpg' || item.fileType == 'jpeg' || item.fileType == '图片'"
                      class="w-100 h-150 mr-10 one_overflow w-136 fs-140 col333 pointer"
                      @click="download(item.fileSrc)" />
                    <video :src="item.fileSrc" controls v-if="item.fileType == 'mp4' || item.fileType == '视频'"
                      class="w-100 h-150 mr-10 one_overflow w-136 fs-140 col333 pointer" />
                    <div class="one_overflow w-200 fs-14 col333 pointer"
                      v-if="item.fileType != 'png' && item.fileType != 'jpg' && item.fileType != 'jpeg' && item.fileType != 'mp4' && item.fileType != '图片' && item.fileType != '视频'"
                      @click="downloadFile(item)">{{ item.fileName }}</div>
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="title == '新增任务' || title == '修改任务'">
        <el-button :loading="loadBtn" @click="submitForm(0)">保 存</el-button>
        <el-button :loading="loadBtn" type="primary" @click="submitForm(1)">发 布</el-button>
      </div>
      <div slot="footer" class="dialog-footer" v-else>
        <el-button :loading="loadBtn" v-show="form.taskStatus != '3'" type="primary"
          v-hasPermi="['project:task:modifyScope']" @click="submitForm(3)">修 改</el-button>
      </div>
    </el-dialog>

    <!-- 选择学生弹窗 -->
    <el-dialog title="" :visible.sync="selecBtn" append-to-body>
      <el-row>
        <el-col :span="24">
          <div class="inforClass">添加学生范围</div>
        </el-col>
      </el-row>
      <el-form :model="queryTreeParams" ref="queryForm" size="small" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="学院">
              <el-select v-model="queryTreeParams.faceXy" multiple collapse-tags filterable clearable
                @change="queryTerr('学院')">
                <el-option v-for="item in proxyList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="专业">
              <el-select v-model="queryTreeParams.faceZy" multiple collapse-tags filterable clearable
                @change="queryTerr('专业')">
                <el-option v-for="item in prozyList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年级">
              <el-select v-model="queryTreeParams.njName" clearable @change="queryTerr('年级')">
                <el-option v-for="item in pronjAllList" :key="item.id" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="班级">
              <el-select v-model="queryTreeParams.faceBj" multiple collapse-tags filterable clearable @change="queryTerr">
                <el-option v-for="item in probjList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="姓名/学号">
              <el-input v-model.trim="filterText" placeholder="输入内容" @input="filterTextNum = ''" clearable />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="学生学号">
              <el-input v-model.trim="filterTextNum" placeholder="输入内容" @input="filterText = ''" clearable />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>

      <el-tree v-loading="loadingTree" :key="treeKey" :data="modifiedTreeData" ref="tree" node-key="value" :props="props"
        show-checkbox :filter-node-method="filterNode" @check="handleCheckChange">
        <template #default="{ node, data }">
          <span
            :class="{ 'level-1': node.level === 1, 'level-2': node.level === 2, 'level-3': node.level === 3, 'level-4': node.level === 4 }">
            {{ node.label }}
          </span>
        </template>
      </el-tree>

      <div style="width: 100%; text-align: center; margin-top: 20px;">
        <el-button type="primary" @click="form.id ? quedingTowBtn() : quedingBtn()"> 保 存 </el-button>
        <el-button @click="selecBtn = false"> 取 消 </el-button>
      </div>
    </el-dialog>

    <el-dialog title="" :visible.sync="selecBtn1" append-to-body @close="closeClick">
      <el-row>
        <el-col :span="24">
          <div class="inforClass">已添加学生</div>
        </el-col>
      </el-row>

      <el-form :model="queryListParams" ref="queryFormList" size="small" label-width="80px">
        <el-row>
          <el-col :span="9">
            <el-form-item label="姓名/学号">
              <el-input v-model.trim="queryListParams.keyword" placeholder="输入内容" clearable @input="handleSearch" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="filteredData" height="500">
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="学号" align="center" prop="stNumber" min-width="120px" />
        <el-table-column label="学院" align="center" prop="xyName" min-width="120px" />
        <el-table-column label="年级" align="center" prop="njName" min-width="80px" />
        <el-table-column label="专业" align="center" prop="zyName" min-width="120px" />
        <el-table-column label="班级" align="center" prop="bjName" min-width="120px" />
      </el-table>
      <div style="width: 100%; text-align: center; margin-top: 20px;" v-if="form.taskStatus != 3">
        <el-button type="primary" @click="addTow"> 添加学生 </el-button>
        <el-button @click="quedingAddBtn"> 保 存({{ prouserAllList.length || 0 }}) </el-button>
        <!-- <el-button @click="selecBtn1 = false"> 取 消 </el-button> -->
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { typeCongfigList } from "@/api/semesManage";
import { projectList, getStudentTree } from "@/api/semesManage";
import { listProxy, listProzy, listProbj, pronjList } from "@/api/project/prold";
import { listTaks, savaTaks, detailTaks, updateTaks, deleteTaks, selectorListTaks, getStudentList, getSelecStudentList } from "@/api/task/index";
export default {
  name: "distributeTasksReleases",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      numbers: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      tableList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dateRangeQuery: [], // 查询
      taksnNumList: [1, 2, 3, 4, 5], // 任务次数
      integralList: [50, 100, 150, 200, 250, 300, 350, 400], // 积分上限
      practiceTypeList: [], // 实践课程
      selectorList: [], // 任务列表
      taskStatusList: [{ id: 0, type: '未发布' }, { id: 1, type: '未开始' }, { id: 2, type: '进行中' }, { id: 3, type: '已结束' }], // 任务状态
      applyStatusList: [{ id: 0, type: '未发布' }, { id: 1, type: '未开始' }, { id: 2, type: '进行中' }, { id: 3, type: '已结束' }], // 报名状态
      // 表单参数
      form: {
        dateRangeQuery: [],
        taskNumber: 1,
        noPassPoints: 0,
        peoplesNumberAstrict: 0,
        participationWay: '',
        applyPassCancelPoints: 0,
        faceXy: [],
        faceZy: [],
        faceBj: [],
        dateRangeApply: []
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: undefined,
        phonenumber: undefined,
        status: undefined,
        practiceType: undefined,
        participationWay: '',
      },
      // 表单校验
      rules: {
        taskName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" },
        ],
        taskRequire: [
          { required: true, message: "任务要求不得为空", trigger: "blur" },
        ],
        practiceType: [
          { required: true, message: "请选择任务类型", trigger: "change" },
        ],
        taskNumber: [{ required: true, message: "请选择任务次数", trigger: "change" }],
        pointsCap: [{ required: true, message: "请选择积分上限", trigger: "change" }],
        dateRangeQuery: [
          { type: 'array', required: true, message: "请选择考试时间段", trigger: "change" },
        ],
        participationWay: [{ required: true, message: "请选择参与方式", trigger: "change" }],
        applyCheck: [{ required: true, message: "请选择报名审核", trigger: "change" }],
        peoplesNumberAstrict: [{ required: true, message: "人数限制不得为空", trigger: "blur" }],
        dateRangeApply: [
          { type: 'array', required: true, message: "请选择报名时间", trigger: "change" },
        ],
      },
      fileList: [],
      fileSize: 200,  // 大小总(MB)
      uploadFileUrl: process.env.VUE_APP_BASE_FILE + "/utils/ossUpload", // 上传文件服务器地址
      uploadList: [], // 上传列表
      number: 0, // 上传图片计数器
      headers: {
        Authorization: "Bearer " + sessionStorage.getItem("token"),
      },
      fielHttp: process.env.VUE_APP_BASE_FILE, // 图片前缀
      selecBtn: false,
      selecBtn1: false,
      props: {
        children: "children", // 使用计算属性
        label: "label",
        value: "value",
        disabled: "disabled"
      },
      treeData: [],
      queryTreeParams: {},
      filterText: '',
      filterTextNum: '',
      proxyList: [],
      prozyList: [],
      pronjAllList: [],
      probjList: [],
      studentIds: [],
      checkedIds: [],
      semesterList: [],
      querySemesterList: [],
      addTree: [],
      cancelData: [],
      prouserList: [], // 接口查询不得更改的数据
      prouserAllList: [], // 不得更改与新增  列表展示
      addProuserList: [], // 新增的学生 暂存
      temporaryList: [], // 新增学生 保存
      deletProuserList: [], // 先新增学生 后删除学生
      treeKey: 1,
      filteredData: [],
      queryListParams: {},
      loadingTree: false,
      loadBtn: false,
    };
  },
  computed: {
    isViewMode() {
      return this.title === '查看任务';
    },
    modifiedTreeData() {
      return this.treeData.map(node => {
        return this.processNode(node);
      });
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    // filterTextNum(val) {
    //   this.$refs.tree.filter(val);
    // },
  },
  async created() {
    // const permissList = sessionStorage.getItem('practiceTypes').split(',');
    // const typeMap = {
    //   1: { type: '劳动教育', id: 1 },
    //   2: { type: '职业素养', id: 2 },
    //   3: { type: '应急安全', id: 3 },
    //   4: { type: '思政实践', id: 4 },
    //   5: { type: '创新创业', id: 5 }
    // };

    // permissList.forEach(v => {
    //   if (typeMap[v]) {
    //     this.practiceTypeList.push(typeMap[v]);
    //   }
    // });
    this.getTypeCongfigList();
    await this.getList();
    this.getListProxy();
    this.getListProzy();
    // this.getListProbj();
    this.getListPronj();
    this.querySemester();
    // await this.getSelectorListTaks();
  },
  mounted() {
    this.$nextTick(this.setupScrollSync);
  },
  methods: {
    getTypeCongfigList() {
      typeCongfigList({
        pageNum: 1,
        pageSize: 50,
      }).then(res => {
        this.practiceTypeList = res.rows;
      });
    },
    setupScrollSync() {
      const headerTable = this.$refs.headerTable;
      const bodyTable = this.$refs.bodyTable;

      if (!headerTable || !bodyTable) return;

      const headerScroll = headerTable.$el.querySelector('.el-table__header-wrapper');
      const bodyScroll = bodyTable.$el.querySelector('.el-table__body-wrapper');

      if (!headerScroll || !bodyScroll) return;

      bodyScroll.addEventListener('scroll', () => {
        headerScroll.scrollLeft = bodyScroll.scrollLeft;
      });

      headerScroll.addEventListener('scroll', () => {
        bodyScroll.scrollLeft = headerScroll.scrollLeft;
      });
    },
    filterNode(value, data) {
      if (Number(value) >= 0) {
        if (!data.children || data.children.length === 0) {
          return data.stNumber.toLowerCase().includes(value.toLowerCase());
        }
      } else {
        if (!data.children || data.children.length === 0) {
          return data.xsName.toLowerCase().includes(value.toLowerCase());
        }
      }
      // return true;
    },
    processNode(node, isHaveBj) {
      if (node.type === 'xy') {
        return {
          type: node.type,
          label: node.xyName,
          xsName: '',
          value: node.xyId + '-' + node.type,
          disabled: (node.isHaveXy || !this.form.id) ? false : true,
          stNumber: '',
          children: node.zyChildList ? node.zyChildList.map(child => this.processNode(child)) : []
        };
      } else if (node.type === 'zy') {
        return {
          type: node.type,
          label: node.zyName,
          xsName: '',
          value: node.zyId + '-' + node.type,
          stNumber: '',
          disabled: (node.isHaveZy || !this.form.id) ? false : true,
          children: node.bjChildList ? node.bjChildList.map(child => this.processNode(child)) : []
        };
      } else if (node.type === 'bj') {
        return {
          type: node.type,
          label: node.bjName,
          xsName: '',
          value: node.bjId + '-' + node.type,
          stNumber: '',
          disabled: (node.isHaveBj || !this.form.id) && !node.studentChildList.every(child => this.prouserList.some(xsIdDis => xsIdDis.userId == child.userId)) ? false : true,
          children: node.studentChildList ? node.studentChildList.map(child => this.processNode(child, node.isHaveBj)) : []
        };
      } else {
        return {
          type: node.type,
          label: node.userName + '(' + node.stNumber + ')',
          xsName: node.userName,
          value: node.userId + '-' + node.type,
          stNumber: node.stNumber,
          xyName: node.xyName,
          xyId: node.xyId,
          zyName: node.zyName,
          zyId: node.zyId,
          bjName: node.bjName,
          bjId: node.bjId,
          njName: node.nj,
          userId: node.userId,
          disabled: (isHaveBj || !this.form.id) && !this.prouserList.some(xsIdDis => xsIdDis.userId == node.userId) ? false : true,
          children: []
        };
      }
    },
    getSemes(e) {
      this.semesterList = [];
      if (e) {
        projectList({
          startTime: e[0] + ' 00:00:00',
        }).then((res) => {
          if (res.code == 200) {
            this.semesterList = res.rows.filter(item => {
              if (
                (new Date(e[1] + ' 23:59:59').getTime() >= new Date(item.startTime).getTime() && new Date(e[1] + ' 23:59:59').getTime() <= new Date(item.endTime).getTime())
                ||
                (new Date(e[0] + ' 00:00:00').getTime() <= new Date(item.startTime).getTime() && new Date(e[1] + ' 23:59:59').getTime() <= new Date(item.endTime).getTime() && new Date(e[1] + ' 23:59:59').getTime() >= new Date(item.startTime).getTime())
                ||
                (new Date(e[0] + ' 00:00:00').getTime() >= new Date(item.startTime).getTime() && new Date(e[1] + ' 23:59:59').getTime() >= new Date(item.endTime).getTime())
                ||
                (new Date(e[0] + ' 00:00:00').getTime() <= new Date(item.startTime).getTime() && new Date(e[1] + ' 23:59:59').getTime() >= new Date(item.endTime).getTime())
              ) {
                return item;
              }
            });
            this.form.semesterConfigId = this.semesterList.length > 0 ? this.semesterList[0].id : null;
          }
        });
      } else {
        this.form.semesterConfigId = null;
      }
    },
    querySemester() {
      projectList().then((res) => {
        if (res.code == 200) {
          this.querySemesterList = res.rows;
        }
      });
    },
    getListSemes(e, id) {
      if (id) {
        projectList({
          pageNum: 1,
          pageSize: 10,
          startTime: e,
        }).then((res) => {
          if (res.code == 200 && res.rows.length > 0) {
            return res.rows.find(v => v.id == id).name;
          } else {
            return '';
          }
        });
      }
    },
    queryTerr(type) {
      if (type == '学院') {
        this.prozyList = [];
        this.queryTreeParams.faceZy = null;
        this.queryTreeParams.faceBj = null;
        this.getListProzy();
      }
      if (type == '专业' || type == '年级') {
        this.queryTreeParams.faceBj = null;
        if (this.prozyList.length > 0) {
          this.getListProbj();
        }
      }
      this.changeSelecStudent();
    },
    // 查询学院
    getListProxy() {
      listProxy().then((response) => {
        this.proxyList = response.rows;
      });
    },
    // 查询专业
    getListProzy() {
      this.prozyList = [];
      listProzy({ xyIds: this.queryTreeParams.faceXy ? this.queryTreeParams.faceXy : this.proxyList.map(v => v.id) }).then((response) => {
        this.prozyList = response.rows;
        this.probjList = [];
        if (response.rows.length > 0) {
          this.getListProbj();
        }
      });
    },
    // 查询班级
    getListProbj() {
      let query = {
        zyIds: this.queryTreeParams.faceZy && this.queryTreeParams.faceZy.length > 0 ? this.queryTreeParams.faceZy : this.prozyList.map(v => v.id),
        njIds: this.queryTreeParams.njName || this.pronjAllList.map(v => v.name)
      };
      listProbj(query).then((response) => {
        this.probjList = response.rows;
      });
    },
    // 查询年级
    getListPronj() {
      pronjList().then((response) => {
        this.pronjAllList = response.rows;
      });
    },
    addTow() {
      this.loadingTree = true;
      this.selecBtn = true;
      this.deletProuserList = [];
      this.temporaryList = [].concat(this.prouserAllList);
      getStudentTree({ practiceTaskId: this.form.id }).then((res) => {
        this.treeData = res.data;
        this.loadingTree = false;
        this.treeKey++;
        this.$nextTick(() => {
          const ids = [...this.prouserAllList.map(v => v.userId ? v.userId + '-xs' : v.value)];
          this.$refs.tree.setCheckedKeys(ids);
        });
      });
    },
    selecStudent() {
      this.queryTreeParams.faceXy = [];
      this.queryTreeParams.faceZy = [];
      this.queryTreeParams.faceBj = [];
      this.queryTreeParams.njName = null;
      this.filterText = '';
      this.queryListParams = {};
      // this.filterTextNum = '';
      if (this.form.id) {
        this.selecBtn1 = true;
        this.filteredData = [].concat(this.prouserAllList);
        // getStudentTree({ practiceTaskId: this.form.id }).then((res) => {
        //   this.treeData = res.data;
        //   this.setCheckedKey();
        // });
      } else {
        this.selecBtn = true;
        this.selecStudents();
      }
      if (this.studentIds.length > 0) {
        this.addTree = [...this.studentIds.map(v => v + '-xs')];
      }
    },
    selecStudents() {
      this.treeData = [];
      this.loadingTree = true;
      const data = {
        xyIds: this.queryTreeParams.faceXy || [],
        zyIds: this.queryTreeParams.faceZy || [],
        bjIds: this.queryTreeParams.faceBj || [],
        njNames: this.queryTreeParams.njName ? [this.queryTreeParams.njName] : [],
      };
      getStudentList(data).then((res) => {
        setTimeout(() => {
          this.treeData = res.data;
          this.loadingTree = false;
          this.setCheckedKey();
        }, 100);
      });
    },
    changeSelecStudent() {
      this.loadingTree = true;
      const data = {
        xyIds: this.queryTreeParams.faceXy || [],
        zyIds: this.queryTreeParams.faceZy || [],
        bjIds: this.queryTreeParams.faceBj || [],
        njNames: this.queryTreeParams.njName ? [this.queryTreeParams.njName] : [],
      };
      getStudentList(data).then((res) => {
        setTimeout(() => {
          this.treeData = res.data;
          this.loadingTree = false;
          // const allCheckedKeys = [...new Set(this.addTree)];
          let allCheckedKeys = [];
          this.addTree.forEach((treeType) => {
            if (treeType.split('-')[1] == 'xs') {
              allCheckedKeys.push(treeType)
            }
          });
          this.$nextTick(() => {
            this.$refs.tree.setCheckedKeys(allCheckedKeys);
            const currentCheckedKeys = this.$refs.tree.getCheckedKeys();
            const halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys();
            this.checkedIds = currentCheckedKeys.concat(halfCheckedKeys);
          });
        }, 100);
      });
    },
    setCheckedKey() {
      this.$nextTick(() => {
        const ids = [...this.studentIds.map(v => v + '-xs')];
        this.$refs.tree.setCheckedKeys(ids);
      });

    },
    handleCheckChange(node, checked) {
      if (this.form.id) {
        checked.checkedNodes.forEach(item => {
          if (item.type == 'xs') {
            this.temporaryList.push({ ...item });
          }
        });
        this.temporaryList = this.temporaryList.filter((user, index, self) => {
          return self.findIndex(u => u.value === user.value) === index;
        });
        if (node.type == 'xy') {
          if (!checked.checkedNodes.some(v => v.value == node.value) && node.children.length > 0) {
            node.children.forEach(c => {
              if (!checked.checkedNodes.some(v => v.value == c.value) && c.children.length > 0) {
                c.children.forEach(y => {
                  if (!checked.checkedNodes.some(v => v.value == y.value) && y.children.length > 0) {
                    y.children.forEach(j => {
                      this.deletProuserList.push({ ...j });
                      this.temporaryList.splice(this.temporaryList.findIndex(q => q.value == j.value), 1);
                    })
                  }
                })
              }
            })
          }
        }
        if (node.type == 'zy') {
          if (!checked.checkedNodes.some(v => v.value == node.value) && node.children.length > 0) {
            node.children.forEach(y => {
              if (!checked.checkedNodes.some(v => v.value == y.value) && y.children.length > 0) {
                y.children.forEach(j => {
                  this.deletProuserList.push({ ...j });
                  this.temporaryList.splice(this.temporaryList.findIndex(q => q.value == j.value), 1);
                })
              }
            })
          }
        }
        if (node.type == 'bj') {
          if (!checked.checkedNodes.some(v => v.value == node.value) && node.children.length > 0) {
            node.children.forEach(j => {
              this.deletProuserList.push({ ...j });
              this.temporaryList.splice(this.temporaryList.findIndex(q => q.value == j.value), 1);
            })
          }
        }
        if (node.type == 'xs') {
          if (!checked.checkedNodes.some(v => v.value == node.value)) {
            this.deletProuserList.push({ ...node });
            this.temporaryList.splice(this.temporaryList.findIndex(q => q.value == node.value), 1);
          }
        }
        this.deletProuserList = this.deletProuserList.filter((user, index, self) => {
          return self.findIndex(u => u.value === user.value) === index;
        });
      }
      const checkedKeys = this.$refs.tree.getCheckedKeys();
      const halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys();
      let checkedIds = checkedKeys.concat(halfCheckedKeys);
      this.addTree = [...new Set([...this.addTree, ...checked.halfCheckedKeys, ...checked.checkedKeys])];
      let cancelData = node;
      // if (!checkedIds.includes(cancelData.value) && this.addTree.find(v => v == cancelData.value)) {
      if (!checkedIds.includes(cancelData.value)) {
        this.addTree = this.addTree.filter(item => item != cancelData.value);
        if (cancelData.type == 'xy') {
          if (cancelData.children.length > 0) {
            cancelData.children.forEach(c => {
              this.addTree = this.addTree.filter(item1 => item1 != c.value);
              if (c.children.length > 0) {
                c.children.forEach(y => {
                  this.addTree = this.addTree.filter(item1 => item1 != y.value);
                  if (y.children.length > 0) {
                    y.children.forEach(j => {
                      this.addTree = this.addTree.filter(item1 => item1 != j.value);
                    });
                  }
                });
              }
            });
          }
        }

        if (cancelData.type == 'zy') {
          if (cancelData.children.length > 0) {
            cancelData.children.forEach(y => {
              this.addTree = this.addTree.filter(item1 => item1 != y.value);
              if (y.children.length > 0) {
                y.children.forEach(j => {
                  this.addTree = this.addTree.filter(item1 => item1 != j.value);
                });
              }
            });
          }
        }

        if (cancelData.type == 'bj') {
          if (cancelData.children.length > 0) {
            cancelData.children.forEach(j => {
              this.addTree = this.addTree.filter(item1 => item1 != j.value);
            });
          }
        }
      }
    },
    changeWay(vla) {
      if (vla == 2) {
        this.form.peoplesNumberAstrict = 0;
        this.form.applyCheck = '0';
      }
    },
    quedingTowBtn() {
      // const mapA = new Map(this.prouserList.map(item => [item.userId + '-xs', item]));
      const mapA = new Map(this.prouserList.map(item => [item.value, item]));
      this.addProuserList = this.temporaryList.filter(itemB => !mapA.has(itemB.value));
      this.addProuserList.forEach(v => {
        const isExist = this.prouserAllList.some(item => item.value === v.value);
        if (!isExist) {
          this.prouserAllList.push({ name: v.xsName, ...v })
        }
      });
      this.queryListParams = {};
      this.deletProuserList = this.deletProuserList.filter(itemB => !this.addProuserList.some(itemA => itemA.value === itemB.value));
      this.filteredData = this.prouserAllList = this.prouserAllList.filter(itemA => !this.deletProuserList.some(itemB => itemB.value === itemA.value));
      this.selecBtn = false;
    },
    quedingAddBtn() {
      this.form.faceXy = [];
      this.form.faceZy = [];
      this.form.faceBj = [];
      this.studentIds = [];
      this.form.faceXy = [...new Set(this.prouserAllList.map(item => item.xyId))];
      this.form.faceZy = [...new Set(this.prouserAllList.map(item => item.zyId))];
      this.form.faceBj = [...new Set(this.prouserAllList.map(item => item.bjId))];
      this.studentIds = [...new Set(this.prouserAllList.map(item => item.userId))];
      this.closeProuserList = [].concat(this.prouserAllList);
      this.selecBtn1 = false;
    },
    closeClick() {
      this.prouserAllList = [].concat(this.closeProuserList);
    },
    quedingBtn() {
      this.addTree = [...new Set(this.addTree)];
      this.studentIds = [];
      this.form.faceXy = [];
      this.form.faceZy = [];
      this.form.faceBj = [];
      this.addTree.forEach(id => {
        if (id.split('-')[1] == 'xy') {
          this.form.faceXy.push(id.split('-')[0]);
        } else if (id.split('-')[1] == 'zy') {
          this.form.faceZy.push(id.split('-')[0]);
        } else if (id.split('-')[1] == 'bj') {
          this.form.faceBj.push(id.split('-')[0]);
        } else if (id.split('-')[1] == 'xs') {
          this.studentIds.push(id.split('-')[0]);
        }
      });
      this.selecBtn = false;
      this.selecBtn1 = false;
      this.studentIds.forEach(v => {
        this.addTree.push(v + '-xs');
      });
      this.addTree = [...new Set(this.addTree)];
    },
    handleInput(value) {
      // const filteredValue = value.replace(/[^\d]/g, '');
      // if (String(value.replace(/[^\d]/g, '')) === 0) {
      //   this.form.peoplesNumberAstrict = 1;
      //   return;
      // }
      // if (!filteredValue || Number(filteredValue) === 0) {
      //   this.form.peoplesNumberAstrict = 1;
      //   return;
      // }
      // if (Number(filteredValue) > this.studentIds.length) {
      //   this.form.peoplesNumberAstrict = this.studentIds.length;
      //   return;
      // }
      this.form.peoplesNumberAstrict = value.replace(/[^\d]/g, '');
    },
    handleInputPoints(value) {
      this.form.applyPassCancelPoints = value.replace(/[^\d]/g, '');
    },
    handleInputPassPoints(value) {
      this.form.noPassPoints = value.replace(/[^\d]/g, '');
    },
    async fetchImage(urls, index) {
      const that = this;
      try {
        const response = await axios.get(this.fielHttp + urls, {
          responseType: 'arraybuffer' // 获取二进制数据
        });
        // 将二进制数据转换为 Base64 格式
        const blob = new Blob([response.data], { type: 'image/jpeg' });
        const imageUrl = URL.createObjectURL(blob);
        // this.fileSrc = imageUrl; // 确保 this 指向正确的上下文
        that.fileList[index].fileSrc = imageUrl;
        that.form.fileList[index].fileSrc = imageUrl;
        that.$forceUpdate();
      } catch (error) {
        console.error('Failed to fetch image:', error);
      }
    },
    getSelectorListTaks() {
      selectorListTaks().then(response => {
        this.selectorList = response.rows;
      })
    },
    sortChange(row) {
      const sortMap = {
        taskName: 'taskNameSort',
        pointsCap: 'pointsCapSort',
        taskNumber: 'taskNumberSort',
      };

      // 提取排序方向的函数
      const getSortOrder = (order) => {
        if (order === 'ascending') return 'asc';
        if (order === 'descending') return 'desc';
        return null;  // 如果不是 'ascending' 或 'descending'，返回 null
      };

      // 获取对应的排序字段和排序方向
      const sortField = sortMap[row.prop];
      const sortOrder = getSortOrder(row.order);

      // 如果找到对应的排序字段，则调用 getList
      if (sortField) {
        this.queryParams.pageNum = 1;
        this.queryParams.pageSize = 10;
        Object.keys(sortMap).forEach((key) => {
          const oldSortField = sortMap[key];
          if (this.queryParams[oldSortField]) {
            delete this.queryParams[oldSortField];
          }
        })
        this.queryParams[sortField] = sortOrder;
        // this.getList({ [sortField]: sortOrder });
        this.getList();
      }
    },
    tiao(row) {
      const query = {
        id: row.id,
        xyIdList: row.faceXy,
        zyIdList: row.faceZy,
        bjIdList: row.faceBj,
        name: row.taskName,
        score: row.pointsCap,
        taskNumber: row.taskNumber,
        type: row.practiceType,
        time: row.startTime.slice(0, 10) + '~' + row.endTime.slice(0, 10),
        semester: row.semesterConfigName,
        statu: this.taskStatusList.find(v => v.id == row.taskStatus).type,
        participationWay: row.participationWay == 1 ? '指定学生参与' : row.participationWay == 2 ? '学生自选报名' : ''
      };
      this.$router.push({ path: '/taskCompletion', query })
    },
    applicaView(row) {
      const query = {
        id: row.id,
        xyIdList: row.faceXy,
        zyIdList: row.faceZy,
        bjIdList: row.faceBj,
        name: row.taskName,
        type: row.practiceType,
        time: row.startTime.slice(0, 10) + '~' + row.endTime.slice(0, 10),
        semester: row.semesterConfigName,
        score: row.peoplesNumberAstrict,
        statu: this.taskStatusList.find(v => v.id == row.taskStatus).type,
        applyPassPeoples: row.applyPassPeoples,
        applyCheck: row.applyCheck == 0 ? '无需审核，直接参与' : '需要审核通过后参与'
      };
      this.$router.push({ path: '/applicaCompletion', query })
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError('上传文件数量不能超过 5 个!');
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传文件，请稍候...");
      this.number++;
      return true;
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.originalFilename, file: res.url });
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.fileUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$modal.closeLoading();
      }
    },
    // 删除文件
    handleDeleteFile(item) {
      const itemIndex = this.fileList.findIndex(file => file.name === item.name);
      this.fileList.splice(itemIndex, 1);
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading()
    },
    beforeClose() {
      this.open = false;
    },
    /** 查询列表 */
    getList() {
      this.tableList = [];
      this.loading = true;
      const time = this.dateRangeQuery && this.dateRangeQuery.length > 0 ? { startTime: this.dateRangeQuery[0] + ' 00:00:00', endTime: this.dateRangeQuery[1] + ' 23:59:59' } : {};
      const query = {
        ...time,
        ...this.queryParams
      };
      delete query.page;
      delete query.limit;
      listTaks(query).then((res) => {
        this.tableList = res.rows;
        this.total = res.total;
        this.loading = false;
      }
      );
    },
    download(url) {
      // window.open(url, '_blank');
      window.open(url);
    },
    async downloadFile(item) {
      if (item.fileType == 'pdf' || item.fileName.split('.')[item.fileName.split('.').length - 1] == 'pdf') {
        try {
          const response = await fetch(process.env.VUE_APP_BASE_FILE + item.file);
          const blob = await response.blob();

          const link = document.createElement("a");
          link.href = URL.createObjectURL(blob); // 创建对象 URL
          link.download = item.fileName; // 设置下载文件名
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          URL.revokeObjectURL(link.href); // 释放对象 URL
        } catch (error) {
          console.error("下载失败：", error);
        }
      } else {
        const link = document.createElement("a");
        link.href = process.env.VUE_APP_BASE_FILE + item.file; // 文件路径
        link.download = item.fileName; // 下载后的文件名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        taskName: undefined,
        taskNumber: 1,
        status: "0",
        noPassPoints: 0,
        applyPassCancelPoints: 0,
        peoplesNumberAstrict: 0,
        pointsCap: '',
        fileList: [],
        dateRangeQuery: [],
        dateRangeApply: [],
        participationWay: '1',
        faceXy: [],
        faceZy: [],
        faceBj: [],
      };
      this.title = null;
      this.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.queryParams.participationWay == 1) {
        this.queryParams.applyStatus = null;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    async resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        taskName: undefined,
        phonenumber: undefined,
        status: undefined,
        practiceType: undefined,
        participationWay: ''
      };
      this.dateRangeQuery = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.$refs.tree ? this.$refs.tree.setCheckedKeys([]) : '';
      this.addTree = [];
      this.prouserList = [];
      this.reset();
      this.form.dateRangeQuery = [];
      this.form.dateRangeApply = [];
      this.studentIds = [];
      this.open = true;
      this.title = "新增任务";
      this.$forceUpdate();
    },

    handleSearch() {
      const keyword = this.queryListParams.keyword.toLowerCase();
      if (!keyword) {
        this.filteredData = this.prouserAllList; // 如果没有关键词，显示所有数据
      } else {
        this.filteredData = this.prouserAllList.filter(item =>
          item.name.toLowerCase().includes(keyword) || item.stNumber.includes(keyword)
        );
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.addTree = [];
      detailTaks(row.id).then(async (response) => {
        this.reset();
        this.form = { ...response.data, participationWay: String(response.data.participationWay), applyCheck: String(response.data.applyCheck) };
        this.studentIds = [...response.data.studentIds];
        this.title = this.form.taskStatus != 0 ? "查看任务" : "修改任务";
        this.form.dateRangeQuery = [response.data.startTime.slice(0, 10), response.data.endTime.slice(0, 10)];
        this.getSemes(this.form.dateRangeQuery);
        if (this.form.participationWay == 2) {
          this.form.dateRangeApply = [response.data.applyStartTime.slice(0, 10), response.data.applyEndTime.slice(0, 10)];
        }

        getSelecStudentList(this.form.id).then((res) => {
          res.rows.forEach(v => { v.bjId = v.clId, v.value = v.userId + '-xs' });
          this.prouserList = res.rows;
          this.prouserAllList = [].concat(res.rows);
          this.closeProuserList = [].concat(this.prouserAllList);
        })

        this.$nextTick(() => {
          this.form.fileList.forEach((item, fileIndex) => {
            // this.fileList.push({ ...item, name: item.fileName, file: this.fetchImage(item.file) })
            this.fileList.push({ ...item, name: item.fileName })
            this.fetchImage(item.file, fileIndex)
          })
        })
        this.open = true;
      });
    },
    // 列表发布按钮
    submitList(row) {
      updateTaks({ ...row, taskStatus: 1, releaseTime: this.getDate() }).then(() => {
        this.$modal.msgSuccess("发布成功");
        this.getList();
      });
    },
    getDate() {
      const now = new Date();

      const year = now.getFullYear();  // 获取年份
      const month = String(now.getMonth() + 1).padStart(2, '0');  // 获取月份，月从 0 开始，所以需要加 1，使用 padStart 补充零
      const day = String(now.getDate()).padStart(2, '0');  // 获取日期，使用 padStart 补充零

      const hours = String(now.getHours()).padStart(2, '0');  // 获取小时，补充零
      const minutes = String(now.getMinutes()).padStart(2, '0');  // 获取分钟，补充零
      const seconds = String(now.getSeconds()).padStart(2, '0');  // 获取秒数，补充零

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    /** 提交按钮 */
    submitForm: function (type) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.studentIds.length == 0) return this.$modal.msgError("请选择学生范围");
          if (this.form.participationWay == 2 && this.form.peoplesNumberAstrict == 0) return this.$modal.msgError("人数限制不得为0");
          if (Number(this.form.peoplesNumberAstrict) > this.studentIds.length) return this.$modal.msgError("人数限制不得大于学生范围人数");
          if (!this.form.dateRangeQuery) return this.$modal.msgError("请选择任务时间");
          if (this.form.participationWay == 2 && this.form.dateRangeApply.length === 0) return this.$modal.msgError("请选择报名时间");
          const { dateRangeQuery, dateRangeApply } = this.form;
          this.form.startTime = `${dateRangeQuery[0]} 00:00:00`;
          this.form.endTime = `${dateRangeQuery[1]} 23:59:59`;
          if (this.form.participationWay == 2) {
            this.form.taskNumber = 1;
            this.form.applyStartTime = `${dateRangeApply[0]} 00:00:00`;
            this.form.applyEndTime = `${dateRangeApply[1]} 23:59:59`;
            if (new Date(this.form.startTime).getTime() < new Date(this.form.applyStartTime).getTime()) return this.$modal.msgError("报名开始时间必须在任务开始时间之前");
            if (new Date(this.form.endTime).getTime() < new Date(this.form.applyEndTime).getTime()) return this.$modal.msgError("报名结束时间必须在任务结束时间之前");
            if (!this.form.peoplesNumberAstrict || this.form.peoplesNumberAstrict == 0) return this.$modal.msgError("人数限制不得为空或为0");
          } else {
            this.form.peoplesNumberAstrict = null;
            this.form.taskNumber = this.form.taskNumber;
          }

          if (this.fileList.length > 0) {
            this.fileList.forEach(item => {
              item.fileName = item.name;
              item.fileType = item.name.split('.').pop();
              // item.type = this.form.practiceType == 1 ? 'ldjy' : this.form.practiceType == 2 ? 'zysy' : this.form.practiceType == 3 ? 'yjaqjy' : this.form.practiceType == 4 ? 'szsjjy' : 'cxcyjy';
            })
          }
          this.form.fileList = this.fileList;
          const data = {
            faceXy: typeof this.form.faceXy == 'object' ? this.form.faceXy.join(',') : this.form.faceXy,
            faceZy: typeof this.form.faceZy == 'object' ? this.form.faceZy.join(',') : this.form.faceZy,
            faceBj: typeof this.form.faceBj == 'object' ? this.form.faceBj.join(',') : this.form.faceBj,
            studentIds: this.studentIds,
            // taskStatus: type,
          };
          this.loadBtn = true;
          if (this.form.id) {
            if (type != 3) {
              this.form.taskStatus == type ? '' : this.form.taskStatus = type;
            } else {
              this.form.taskStatus = 1;
            }
            type === 1 ? this.form.releaseTime = this.getDate() : ''
            updateTaks({ ...this.form, ...data }).then((response) => {
              if (type == 1) {
                this.$modal.msgSuccess("发布成功");
              } else {
                this.$modal.msgSuccess("修改成功");
              }
              this.loadBtn = false;
              this.open = false;
              this.title = null;
              this.getList();
            });
          } else {
            savaTaks({ ...this.form, ...data, taskStatus: type }).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.loadBtn = false;
              this.title = null;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const that = this;
      let loading = null;
      this.$modal
        .confirm('是否确认删除"' + row.taskName + '"任务的数据项？')
        .then(function () {
          loading = that.$loading({
            lock: true,
            text: '处理中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          return deleteTaks(row.id);
        })
        .then(() => {
          loading.close();
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
          if (loading) {
            loading.close();
          }
        });
    },
    /** 撤回按钮操作 */
    handleWithdraw(row) {
      const that = this;
      let loading = null;
      this.$modal
        .confirm('是否撤回"' + row.taskName + '"的实践任务,撤回后学生无法查看任务')
        .then(function () {
          loading = that.$loading({
            lock: true,
            text: '处理中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          return updateTaks({ ...row, taskStatus: 0 });
        })
        .then(() => {
          loading.close();
          this.getList();
          this.$modal.msgSuccess("撤回成功");
        })
        .catch(() => {
          if (loading) {
            loading.close();
          }
        });
    },
  },
};
</script>
<style scoped lang="scss">
.fileImage {
  display: flex;
  overflow-x: auto;
}

::v-deep .el-dialog__body {
  padding-top: 0 !important;
  padding-bottom: 10px !important;
}

#fileId {
  ::v-deep .el-form-item__content {
    margin-left: 20px !important;
  }
}

.hide-close-icon {
  ::v-deep .el-tag__close {
    display: none !important;
  }
}

.inforClass {
  font-size: 16px;
  font-weight: 700;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.inforClass::before {
  content: '';
  width: 5px;
  height: 25px;
  background-color: #419eff;
  margin-right: 10px;
  display: inline-block;
}

::v-deep .el-select {
  width: 100% !important;
}

::v-deep .el-tree {
  min-height: 300px !important;
}

::v-deep ::-webkit-scrollbar {
  height: 15px !important;
}

.double-table-container {
  position: relative;
  width: 100%;
}

.header-table-wrapper {
  overflow-x: auto;
  /* 强制显示水平滚动条 */
  overflow-y: hidden;
  background: #f5f7fa;
  border-bottom: 1px solid #dfe6ec;

  ::v-deep .el-table__empty-text {
    display: none !important;
  }

  ::v-deep .el-table__empty-block {
    height: 1px !important;
    min-height: 0 !important;
    visibility: hidden !important;
  }

  ::v-deep .el-table__header {
    visibility: hidden !important;
  }

  ::v-deep th {
    height: 1px !important;
    padding: 0;
    line-height: 0 !important;

    .caret-wrapper {
      display: none;
    }

    .cell {
      line-height: 0;
    }
  }
}

.level-1 {
  font-size: 15px;
  font-weight: 600;
}

.level-2 {
  font-size: 14px;
  // font-weight: 600;
}

.level-3 {
  font-size: 14px;
  // font-weight: 500;
}

.level-4 {
  font-size: 12px;
}

/* 隐藏顶部表格的数据部分 */
.header-table-wrapper .el-table__body-wrapper {
  display: none !important;
}

/* 隐藏主表格的表头 */
.body-table-wrapper .el-table__header-wrapper {
  display: none !important;
}

::v-deep .el-tree-node .el-tree-node__children .el-tree-node__children .el-tree-node__children {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: flex-start;

  .el-tree-node {
    width: 33.33%;
  }
}
</style>
